package model

import (
	"common/helper"
	"database/sql"
	"errors"
	"fmt"
	g "github.com/doug-martin/goqu/v9"
)

type TblPromoWeekBetConfig struct {
	Id          string  `json:"id" db:"id" cbor:"id"`
	FlowAmount  float64 `json:"flow_amount" db:"flow_amount" cbor:"flow_amount"`
	BonusAmount float64 `json:"bonus_amount" db:"bonus_amount" cbor:"bonus_amount"`
	UpdatedAt   int64   `json:"updated_at" db:"updated_at" cbor:"updated_at"`
	UpdatedName string  `json:"updated_name" db:"updated_name" cbor:"updated_name"`
}

type PromoWeeklyConfigData struct {
	D []TblPromoWeekBetConfig `json:"d" cbor:"d"`
	T int64                   `json:"total" cbor:"t"`
	S uint                    `json:"s" cbor:"s"`
}

type TblPromoWeekbetRecord struct {
	Id              string  `json:"id" db:"id"`
	Uid             string  `json:"uid" db:"uid"`
	ReportTime      int64   `json:"report_time" db:"report_time"`
	ValidBetAmount  float64 `json:"valid_bet_amount" db:"valid_bet_amount"`
	WaitBonusAmount float64 `json:"wait_bonus_amount" db:"wait_bonus_amount"`
	BonusAmount     float64 `json:"bonus_amount" db:"bonus_amount"`
	State           int     `json:"state" db:"state"`
	UpdatedAt       int64   `json:"updated_at" db:"updated_at"`
	Remark          string  `json:"remark" db:"remark"`
	PayAt           int64   `json:"pay_at" db:"pay_at"`
}

type PromoWeekbetRecordData struct {
	D []TblPromoWeekbetRecord `json:"d" cbor:"d"`
	T int64                   `json:"total" cbor:"t"`
	S uint                    `json:"s" cbor:"s"`
}

func PromoWeeklyConfigInsert(data TblPromoWeekBetConfig) error {

	data.Id = helper.GenId()
	query, _, _ := dialect.Insert("tbl_promo_weekbet_config").Rows(&data).ToSQL()
	_, err := meta.MerchantDB.Exec(query)
	if err != nil {
		return pushLog(fmt.Errorf("%s,[%s]", err.Error(), query), "数据库错误")
	}

	return nil
}

func PromoWeeklyConfigUpdate(id string, data TblPromoWeekBetConfig) error {

	query, _, _ := dialect.Update("tbl_promo_weekbet_config").Set(&data).Where(g.Ex{"id": id}).ToSQL()

	_, err := meta.MerchantDB.Exec(query)
	if err != nil {
		return pushLog(fmt.Errorf("%s,[%s]", err.Error(), query), "数据库错误")
	}

	return nil
}

func PromoWeeklyConfigList(page, pageSize uint, ex g.Ex) (PromoWeeklyConfigData, error) {

	data := PromoWeeklyConfigData{}
	t := dialect.From("tbl_promo_weekbet_config")
	if page >= 1 {
		query, _, _ := t.Select(g.COUNT(1)).Where(ex).ToSQL()

		err := meta.MerchantDB.Get(&data.T, query)
		if err != nil {
			return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), query), "数据库错误")
		}

		if data.T == 0 {
			return data, nil
		}
	}

	offset := (page - 1) * pageSize
	query, _, _ := t.Select(colsPromoWeeklyConfig...).Where(ex).Offset(offset).Limit(pageSize).Order(g.C("flow_amount").Asc()).ToSQL()

	err := meta.MerchantDB.Select(&data.D, query)
	if err != nil && err != sql.ErrNoRows {
		return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), query), "数据库错误")
	}

	data.S = pageSize
	return data, nil
}

func PromoWeekbetRecordList(page, pageSize uint, ex g.Ex) (PromoWeekbetRecordData, error) {

	data := PromoWeekbetRecordData{}
	t := dialect.From("tbl_promo_weekbet_record")
	if page >= 1 {
		query, _, _ := t.Select(g.COUNT(1)).Where(ex).ToSQL()

		err := meta.MerchantDB.Get(&data.T, query)
		if err != nil {
			return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), query), "数据库错误")
		}

		if data.T == 0 {
			return data, nil
		}
	}

	offset := (page - 1) * pageSize
	query, _, _ := t.Select(colsPromoWeekbetRecord...).Where(ex).Offset(offset).Limit(pageSize).Order(g.C("id").Asc()).ToSQL()

	err := meta.MerchantDB.Select(&data.D, query)
	if err != nil && err != sql.ErrNoRows {
		return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), query), "数据库错误")
	}

	data.S = pageSize
	return data, nil
}

func MerchantPromoWeekbetRecordList(page, pageSize uint, uid, operatorId string) (PromoWeekbetRecordData, error) {

	data := PromoWeekbetRecordData{}

	ex := g.Ex{}
	uids := make([]string, 0)
	if uid != "" {
		mb, err := MemberFindByUidAndOpeId(uid, operatorId)
		if err != nil {
			return data, errors.New(helper.OperatorIdErr)
		}
		ex["uid"] = mb.Uid
	} else {
		members, err := MemberFindByOperatorId(operatorId)
		if err != nil {
			return data, errors.New(helper.OperatorIdErr)
		}
		if len(members) > 0 {
			for _, val := range members {
				uids = append(uids, val.Uid)
			}
			ex["uid"] = uids
		}
	}

	t := dialect.From("tbl_promo_weekbet_record")
	if page >= 1 {
		query, _, _ := t.Select(g.COUNT(1)).Where(ex).ToSQL()

		err := meta.MerchantDB.Get(&data.T, query)
		if err != nil {
			return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), query), "数据库错误")
		}

		if data.T == 0 {
			return data, nil
		}
	}

	offset := (page - 1) * pageSize
	query, _, _ := t.Select(colsPromoWeekbetRecord...).Where(ex).Offset(offset).Limit(pageSize).Order(g.C("id").Asc()).ToSQL()

	err := meta.MerchantDB.Select(&data.D, query)
	if err != nil && err != sql.ErrNoRows {
		return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), query), "数据库错误")
	}

	data.S = pageSize
	return data, nil
}

func BusinessPromoWeekbetRecordList(page, pageSize uint, uid, businessId string) (PromoWeekbetRecordData, error) {

	data := PromoWeekbetRecordData{}

	ex := g.Ex{}
	uids := make([]string, 0)
	if uid != "" {
		mb, err := MemberFindByUidAndProId(uid, businessId)
		if err != nil {
			return data, errors.New(helper.BusinessIdErr)
		}
		ex["uid"] = mb.Uid
	} else {
		members, err := MemberFindByBusinessId(businessId)
		if err != nil {
			return data, errors.New(helper.BusinessIdErr)
		}
		if len(members) > 0 {
			for _, val := range members {
				uids = append(uids, val.Uid)
			}
			ex["uid"] = uids
		}
	}

	t := dialect.From("tbl_promo_weekbet_record")
	if page >= 1 {
		query, _, _ := t.Select(g.COUNT(1)).Where(ex).ToSQL()

		err := meta.MerchantDB.Get(&data.T, query)
		if err != nil {
			return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), query), "数据库错误")
		}

		if data.T == 0 {
			return data, nil
		}
	}

	offset := (page - 1) * pageSize
	query, _, _ := t.Select(colsPromoWeekbetRecord...).Where(ex).Offset(offset).Limit(pageSize).Order(g.C("id").Asc()).ToSQL()

	err := meta.MerchantDB.Select(&data.D, query)
	if err != nil && err != sql.ErrNoRows {
		return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), query), "数据库错误")
	}

	data.S = pageSize
	return data, nil
}
